<template>
  <div style="width: 100%">
    <a class="btn" v-show="isCodeShow" @click="sendEmailCodeHandle">
      <span>获取验证码</span>
    </a>
    <button class="btn" v-show="!isCodeShow" style="background: #888">
      等待 {{ count }} 秒
    </button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { sendEmailCode } from '@/utils/http/login'

const props = defineProps<{
  email: string
}>()
const isCodeShow = ref<boolean>(true)
const count = ref<number>(0)
let timer: {} | NodeJS.Timeout = {}
const sendEmailCodeHandle = () => {
  const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
  if (!reg.test(props.email)) return ElMessage.error('邮箱格式错误')
  let TIME_COUNT = 60
  if (Object.keys(timer).length == 0) {
    count.value = TIME_COUNT
    isCodeShow.value = false
    timer = setInterval(() => {
      if (count.value > 0 && count.value <= TIME_COUNT) {
        count.value--
      } else {
        isCodeShow.value = true
        clearInterval(timer as NodeJS.Timeout)
        timer = {}
      }
    }, 1000)
  }
  sendEmailCode(props.email).then((res) => {
    ElMessage.success('验证码已发送到您的邮箱，请注意查收')
  })
}
</script>

<style lang="scss" scoped>
.btn {
  height: 30px;
  display: inline-block;
  border-radius: 4px;
  background-color: #3d405b;
  border: none;
  color: #ffffff;
  text-align: center;
  font-size: 15px;
  width: 100%;
  transition: all 0.5s;
  cursor: pointer;
  line-height: 30px;
}

.btn span {
  cursor: pointer;
  display: inline-block;
  position: relative;
  transition: 0.5s;
}

.btn span:after {
  content: '»';
  position: absolute;
  opacity: 0;
  top: 0;
  right: -15px;
  transition: 0.5s;
}

.btn:hover span {
  padding-right: 15px;
}

.btn:hover span:after {
  opacity: 1;
  right: 0;
}
</style>
